﻿using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using API;
using AVFoundation;
using CoreGraphics;
using CoreMedia;
using Foundation;
using libmp.MyExtensions;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using UIKit;

namespace libmp
{
    class UIPlaybackControllView : UIView
    {
        static ILog logger = App.logger;

        UIView vBufferBg = new UIView();
        UIView vBufferFg = new UIView();
        UISlider slider = new UISlider();
        UIButton btnPlay = new UIButton();
        UIButton btnFullscreen = new UIButton();
        UIActivityIndicatorView loadingView;
        UILabel labTime = new UILabel();
        CGSize contentSize;
        AVPlayer player;
        NSDateFormatter dateFormatter;
        System.Timers.Timer tmUpdate;
        UIView rootView;
        bool isDragging;

        public UIPlaybackControllView()
        {
            UserInteractionEnabled = true;
            TranslatesAutoresizingMaskIntoConstraints = false;
            BackgroundColor = UIColor.Black.ColorWithAlpha(0.8f);
            contentSize = new CGSize(250, 40);

            dateFormatter = new NSDateFormatter();
            dateFormatter.TimeZone = NSTimeZone.FromName("UTC");
            dateFormatter.DateFormat = "HH:mm:ss";

            btnPlay.SetParent(this);
            btnPlay.SetImage(Util.UIImageFromHotFile("slider/play.png").ToRetina(2).WithColor(Util.MainColor), UIControlState.Normal);
            btnPlay.SetImage(Util.UIImageFromHotFile("slider/pause.png").ToRetina(2).WithColor(Util.MainColor), UIControlState.Selected);
            // btnPlay.BackgroundColor = UIColor.Green;
            btnPlay.TranslatesAutoresizingMaskIntoConstraints = false;
            btnPlay.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(this);
                m.Left.EqualTo(this).Offset(10);
                // m.Width.EqualTo(NSObject.FromObject(50));
            });
            btnPlay.TouchUpInside += (s, e) =>
            {
                if (IsPlaying())
                    player.Pause();
                else
                    player.Play();
                Update();
            };

            btnPlay.Hidden = true;
            loadingView = new UIActivityIndicatorView();
            loadingView.TranslatesAutoresizingMaskIntoConstraints = false;
            loadingView.HidesWhenStopped = false;
            loadingView.SetParent(this);
            loadingView.MakeConstraints(m => m.Center.EqualTo(btnPlay));

            btnFullscreen.SetParent(this);
            btnFullscreen.SetImage(Util.UIImageFromHotFile("slider/full.png").ToRetina(2).WithColor(Util.MainColor), UIControlState.Normal);
            btnFullscreen.TranslatesAutoresizingMaskIntoConstraints = false;
            btnFullscreen.MakeConstraints(m =>
            {
                m.Right.EqualTo(this).Offset(-10);
                m.CenterY.EqualTo(this);
            });
            btnFullscreen.TouchUpInside += (s, e) =>
            {
                toggleFullScreen();
            };

            labTime.SetParent(this);
            labTime.TextColor = UIColor.White;
            labTime.Text = "10:30:29";
            labTime.Font = UIFont.SystemFontOfSize(12);
            labTime.MakeConstraints(m =>
            {
                m.Right.EqualTo(btnFullscreen.Left()).Offset(-10);
                m.Width.EqualTo(NSObject.FromObject(60));
                m.CenterY.EqualTo(this);
            });

            vBufferBg.SetParent(this);
            vBufferFg.SetParent(this);

            slider.SetParent(this);
            slider.TintColor = Util.MainColor;
            slider.SetThumbImage(Util.UIImageFromHotFile("slider/circle.png").ToRetina(6).WithColor(Util.MainColor), UIControlState.Normal);
            slider.MaximumTrackTintColor = UIColor.Clear;
            // slider.SetMinTrackImage(mb.Util.MakeColorImage(new CGSize(200, 2), Util.MainColor).CreateResizableImage(new UIEdgeInsets(0, 0, 0, 0)), UIControlState.Normal);
            // slider.SetMaxTrackImage(mb.Util.MakeColorImage(new CGSize(200, 2), UIColor.Clear).CreateResizableImage(new UIEdgeInsets(0, 0, 0, 0)), UIControlState.Normal);
            // slider.BackgroundColor = UIColor.Blue;
            slider.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(this);
                m.Left.EqualTo(btnPlay.Right()).Offset(10);
                m.Right.EqualTo(labTime.Left()).Offset(-10);
            });

            slider.TouchDown += (s, e) => { isDragging = true; };
            slider.TouchCancel += (s, e) => { isDragging = false; };
            slider.TouchUpInside += (s, e) => { isDragging = false; };
            slider.ValueChanged += (s, e) =>
            {
                logger.Log("drag changed", slider.Value);
                player?.Seek(CMTime.FromSeconds(slider.Value, 60000));
            };

            vBufferBg.MakeConstraints(m =>
            {
                m.Left.EqualTo(slider);
                m.CenterY.EqualTo(slider);
                m.Height.EqualTo(NSObject.FromObject(2));
                m.Width.EqualTo(slider);
            });
            vBufferBg.BackgroundColor = UIColor.FromRGB(150, 150, 150);
            vBufferBg.UserInteractionEnabled = false;

            vBufferFg.BackgroundColor = Util.MainColor.Darker(0.6f);
            vBufferFg.UserInteractionEnabled = false;

            BufferPrgress = 0.7f;
        }

        float BufferPrgress
        {
            set
            {
                vBufferFg.RemakeConstraints(m =>
                {
                    m.Left.EqualTo(slider);
                    m.CenterY.EqualTo(slider);
                    m.Height.EqualTo(NSObject.FromObject(2));
                    m.Width.EqualTo(slider).MultipliedBy(value);
                });
            }
        }

        public override CGSize IntrinsicContentSize
        {
            get
            {
                // logger.Log("customeview", contentSize);
                return contentSize;
            }
        }

        public UIView RootView
        {
            set
            {
                rootView = value;
            }
        }

        public AVPlayer avPlayer
        {
            set
            {
                player = value;
                if (tmUpdate != null) tmUpdate.Stop();
                tmUpdate = new System.Timers.Timer() { Interval = 100, Enabled = true };
                tmUpdate.Elapsed += (s, e) =>
                {
                    this.InvokeOnMainThread(() =>
                    {
                        Update();
                    });
                };

                slider.MinValue = 0;
                var total = player.CurrentItem.Asset.Duration;
                slider.MaxValue = (float) total.Seconds;
                Update();
            }
        }

        public void Stop()
        {
            if (tmUpdate != null)
            {
                tmUpdate.Stop();
                tmUpdate = null;
            }
        }
        bool IsPlaying()
        {

            return (int) player.TimeControlStatus == (int) AVPlayerTimeControlStatus.Playing;
        }

        void Update()
        {
            var total = player.CurrentItem.Asset.Duration;
            var now = player.CurrentItem.CurrentTime;
            var date = NSDate.FromTimeIntervalSince1970(now.Seconds);
            labTime.Text = dateFormatter.ToString(date);

            if (!isDragging)
                slider.Value = (float) now.Seconds;

            var trList = player.CurrentItem.LoadedTimeRanges;
            if (trList.Length > 0)
            {
                var tr = trList[trList.Length - 1].CMTimeRangeValue;
                // logger.Log("range", tr.Start.Seconds, tr.Duration.Seconds);
                BufferPrgress = (float) ((tr.Start.Seconds + tr.Duration.Seconds) / total.Seconds);
            }

            // logger.Log("cur", date, player.TimeControlStatus);

            if ((int) player.TimeControlStatus == (int) AVPlayerTimeControlStatus.Playing)
            {
                btnPlay.Selected = true;
                btnPlay.Hidden = false;
                loadingView.Hidden = true;
            }
            else if ((int) player.TimeControlStatus == (int) AVPlayerTimeControlStatus.Paused)
            {
                btnPlay.Selected = false;
                btnPlay.Hidden = false;
                loadingView.Hidden = true;
            }
            else
            {
                btnPlay.Hidden = true;
                loadingView.Hidden = false;
                loadingView.StartAnimating();
            }
        }

        void toggleFullScreen()
        {
            logger.Log("toggle fullscreen");
            UIView movieView = this.Superview;
            // var size = UIScreen.MainScreen.Bounds;
            // movieView.Frame = new CGRect(0, 0, size.Width, size.Height);
            // movieView.Frame = new CGRect(0, 0, size.Height, size.Width);
            // movieView.RemoveFromSuperview();
            // movieView.SetParent(rootView);
            // movieView.Transform = CGAffineTransform.MakeIdentity();
            // movieView.Transform = CGAffineTransform.MakeRotation(0.5f * (float) Math.PI);

            UIDevice.CurrentDevice.SetValueForKey(NSObject.FromObject((int) UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
        }
    }
}